package be.kuleuven.peno3.mobiletoledo.server;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import org.json.simple.JSONObject;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@Path ("/QueueHandler")
public class QueueServer {

	protected DatabaseManager manager = DatabaseManager.getInstance();
	
	@GET
	@Path ("/getLength")
	@Produces ("application/json")
	public String getLength(@QueryParam("location") String location){
		String query = "SELECT * FROM Queue WHERE location='"+location+"' ORDER BY id DESC LIMIT 1";
	    
		String result = queryForMessages(query);
		manager.disconnect();
		return result;
	}
	
	@GET
	@Path ("/getLengthHistory")
	@Produces ("application/json")
	public String getLengthHistory(@QueryParam("location") String location){
		String query = "SELECT * FROM Queue WHERE location='"+location+"' ORDER BY id DESC LIMIT 10";
	    
		String result = queryForMessages(query);
		manager.disconnect();
		return result;
	}
	
	@SuppressWarnings({ "unchecked" })
	@GET
	@Path ("/addLength")
	@Produces ("application/json")
	public String addLength(@QueryParam("author") String author, @QueryParam("when") String when, @QueryParam("length") int length, @QueryParam("location") String location){
		JSONObject result = new JSONObject();
		try {
			String query = "INSERT INTO Queue(author, `when`, length, location) VALUES ('"+author+"','"+when+"','"+length+"','"+location+"')";
			manager.update(query);
			
			manager.disconnect();
		} catch (SQLException e1) {
			result.put("result", "INSERT of credentials failed");
			e1.printStackTrace();
			return result.toString();
		}
		
		result.put("result", "QueueInfo successfully added");
		manager.disconnect();
		return result.toString();
	}
	
	@SuppressWarnings("static-access")
	private String queryForMessages(String query) {
		JsonArray queue = new JsonArray();
		ResultSet rs = manager.query(query);
		Gson gson = new Gson();
		try {
			while(rs.next()) {
				JsonObject queueInfo = (JsonObject) gson.toJsonTree(manager.getColumnValues(rs));

				queue.add(queueInfo);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (NullPointerException ex) {
			ex.printStackTrace();
		}
		String asString = queue.toString();
		return asString;
	}
}
